<template>
    <div id="BranchesAndLeaf">
        <el-container>
            <el-header>
                <el-form size="min" inline>
                    <el-form-item label="输入关键字" >
                        <!-- 输入框 -->
                        <el-input v-model="key" :placeholder="placeholder" clearable></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary"  @click="Search">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary"  @click="Back">返回</el-button>
                    </el-form-item>
                </el-form>
            </el-header>
            <el-container style="height:100vh;">
                <el-aside :style="{width:asideWith}"  v-show="isShow==true">

                    <el-scrollbar  :style="treeStyle" >
                        <template v-if="lazy==true">
                            <el-tree
                                :props="props"
                                :load="loadNode"
                                node-key="No"
                                lazy
                                @node-click="treeNodeClick">
                            </el-tree>
                        </template>
                        <template v-else>
                            <el-tree
                                    :props="props"
                                    :data="treeData"
                                    node-key="No"
                                    :check-strictly="true"
                                    default-expand-all
                                    @node-click="handleNodeClick"
                            ></el-tree>
                        </template>
                    </el-scrollbar>
                </el-aside>
                <el-container>
                    <el-main>
                        <el-table :data="tableData"  border
                                  :header-cell-style="{background:'#f5f7fab5',color:'#777'}"
                                  @selection-change="handleSelectionChange"
                                  @select="Rowselect"
                                  ref="table">
                            <el-table-column
                                    type="selection"
                                    width="55">
                            </el-table-column>
                            <el-table-column v-for="item in tableColumnData"  :key="item.field" :label="item.text" :prop="item.field"  :width="item.width"   :show-overflow-tooltip='true'>
                            </el-table-column>
                        </el-table>
                        <el-table :data="selTableData"  border
                                  :header-cell-style="{background:'#f5f7fab5',color:'#777'}"
                                  ref="seltable">
                            <el-table-column
                                    prop="No"
                                    label="编号">
                            </el-table-column>
                            <el-table-column
                                    prop="Name"
                                    label="姓名">
                            </el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button
                                            size="mini"
                                            type="danger"
                                            @click="handleDelete(scope.$index)">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-main>

                </el-container>
            </el-container>
        </el-container>

    </div>
</template>
<script>
    export default {
        name: "Branches",
        props: {
            mapExt: {
                type: Object
            },
            selectRow: {
                type: Array,
                default: () => []
            },
        },
        data() {
            return {
                params: {},//参数
                webUser: {},
                selectType:true,//是否多选
                rootNo:"0",//根节点

                //查询条件
                key:"",
                placeholder:"",
                lazy:false,
                //树形结构
                props:{
                    children: "children",
                    label: "Name",
                    isLeaf: 'leaf'
                },
                isShow:true,
                asideWith:"50%",
                treeStyle:{
                    'height':document.documentElement.clientHeight*0.65+'px',
                    'overflow-x':'hidden'
                },
                treeData:[],
                treeChecked:[],

                //右侧上方表格
                tableData:[],
                tableColumnData:[],
                //数据选择的表格
                selTableData:[]

            }
        },
        created() {
            this.params = this.$store.getters.getData;
            this.webUser = this.$store.getters.getWebUser;
            this.placeholder = this.GetPara(this.mapExt.AtPara,"SearchTip");
            this.selectType = this.GetPara(this.mapExt.AtPara,"SelectType")=="0"?false:true;
            this.rootNo = this.mapExt.Doc;
            if (this.rootNo == "@WebUser.FK_Dept") {
                this.rootNo = this.webUser.FK_Dept;
            }
            if (this.rootNo == "@WebUser.OrgNo") {
                this.rootNo = this.webUser.OrgNo;
            }
            if (this.rootNo == null || this.rootNo == undefined) {
                this.rootNo = "0"
            }
            let treeUrl = this.mapExt.Tag2;
            treeUrl = treeUrl.replace(/~/g,"'");
            if(treeUrl.toLowerCase() .indexOf("parentno='@key'")!=-1)
                this.lazy=true;
            if(this.lazy==false){
                let json = this.loadTreeData(this.rootNo);
                this.treeData =this.findChildren(json,this.rootNo);
            }


            this.loadTableColumn();
            this.selTableData=this.selectRow;
            this.$nextTick(()=>{
                this.selTableData.forEach(row => {
                    this.$refs.table.toggleRowSelection(row,true);
                });
                this.selTableData.forEach(row => {
                    this.$refs.seltable.toggleRowSelection(row,true);
                });
            });
        },
        methods:{
            loadNode(node, resolve) {
                if (node.level === 0) {
                    this.loadTableData(node.key);
                    return resolve(this.loadTreeData(this.rootNo));
                }
                if (node.level >= 1){
                    this.loadTableData(node.key);
                    return resolve(this.loadTreeData(node.key));
                }
            },
            treeNodeClick(data,node){
                this.loadTableData(node.key);
            },
            handleNodeClick(node){
                this.loadTableData(node.No);
            },
            loadTableColumn(){
                let columns = this.mapExt.Tag;
                //显示列的中文名称.
                if (typeof columns == "string" && columns!="") {
                    columns.split(",").forEach(item=>{
                        var exp = item.split("=");
                        var field;
                        var title;
                        if (exp.length == 1) {
                            field = title = exp[0];
                        } else if (exp.length == 2) {
                            field = exp[0];
                            title = exp[1];
                        }
                        if (!this.isLegalName(field)) {
                            return true;
                        }
                        this.tableColumnData.push({
                            field: field,
                            text: title
                        });
                    });
                } else {
                    this.tableColumnData.push({
                        field:  'No',
                        text: '编号'
                    });
                    this.tableColumnData.push({
                        field:  'Name',
                        text: '名称'
                    });
                }
            },

            loadTreeData(parentNo){
                let treeUrl = this.mapExt.Tag2;
                treeUrl = treeUrl.replace(/@Key/g,parentNo);
                let json=null;
                //SQL查询
                if(this.mapExt.DBType==0)
                    json = this.GetDataTableByField("Tag2", parentNo);
                else
                    json = this.DBAccess.RunDBSrc(treeUrl, this.mapExt.DBType);
                return json;
            },
            loadTableData(key){
                if (this.mapExt.DBType == 0) {
                    this.tableData = this.GetDataTableByField("Tag3", key);
                } else {
                   let dbSrc = this.mapExt.replace(/@Key/g,key);
                    //获得json.
                    this.tableData = this.DBAccess.RunDBSrc(dbSrc, this.mapExt.DBType);
                }
            },
            handleSelectionChange(val) {
                if (this.selectType == false) {
                    if (val.length > 1) {
                        this.$refs.table.clearSelection()
                        this.$refs.table.toggleRowSelection(val[val.length - 1]);
                    }

                }
                let arry = this.$refs.table.store.states.selection;
                if (this.selectType == false){
                    if(arry.length!=0)
                        this.selTableData = arry;

                }

            },
            Rowselect(selection, row){
                let isHave=false;
                let selected = selection.length && selection.indexOf(row) !== -1
                this.selTableData.forEach(item=>{
                    if(row.No==item.No){
                        if(selected == false){
                            this.selTableData.pop(row);
                            isHave=true;
                            return false;
                        }
                        isHave=true;
                        return false;
                    }
                });
                if(isHave==false)
                    this.selTableData.push(row);
            },

            handleDelete(index) {
                this.selTableData.splice(index,1);
            },
            Search(){
                this.isShow = false;
                this.asideWith="0%";
                if (this.mapExt.DBType == 0) {
                    this.tableData = this.GetDataTableByField("Tag1", this.key);
                } else {
                    let dbSrc = this.mapExt.Tag1;
                    dbSrc = dbSrc.replace(/@Key/g,this.key)
                    //获得json.
                    this.tableData = this.DBAccess.RunDBSrc(dbSrc, this.mapExt.DBType);
                }
            },
            Back(){
                this.isShow = true;
                this.asideWith="50%";
            },
            GetDataTableByField(field,keyVal){
                let en = new this.Entity("BP.Sys.MapExt", this.mapExt);
                en.MyPK = this.mapExt.MyPK;
                let json = en.DoMethodReturnString("GetDataTableByField", field, "@Key=" + keyVal, null, this.params.WorkID);
                if (json.indexOf("err@") != -1) {
                    alert(json);
                    return "";
                }
                json = JSON.parse(json);
                return json;
            },
            isLegalName(name) {
                if (!name) {
                    return false;
                }
                return name.match(/^[a-zA-Z\$_][a-zA-Z\d\$_]*$/);
            },
            findChildren :function(jsonArray, parentNo) {
                let appendToTree = function (treeToAppend, child) {
                    treeToAppend.forEach(o=>{
                        if (o.No == child.ParentNo) {
                            o.children.push({
                                "No": child.No,
                                "Name": child.Name,
                                "children": [],
                            });
                        } else {
                            appendToTree(o.children, child);
                        }
                    });
                };

                let jsonTree = [];
                if (jsonArray instanceof Array  && typeof parentNo !== "undefined") {
                    //如果parentNo不为0，则增加parentNo的部门数据
                    if (parentNo != 0) {
                        jsonArray.forEach( item=>{
                            if (item.No == parentNo) {
                                jsonTree.push({
                                    "No": parentNo,
                                    "Name": item.Name,
                                    "children": []
                                });
                                return;
                            }
                        });
                    }
                    jsonArray.forEach( o=>{
                        if (o.ParentNo == parentNo) {
                            jsonTree.push({
                                "No": o.No,
                                "Name": o.Name,
                                "children": [],
                            });
                        } else {
                            appendToTree(jsonTree, o);
                        }
                    });
                }

                function _(treeArray) {
                    treeArray.forEach(o=>{
                        if (o.children instanceof Array) {
                            if (o.children.length == 0){
                            } else {
                                _(o.children);
                            }
                        }
                    });
                }
                _(jsonTree);
                return jsonTree;
            }
        },
        watch:{
            selTableData(){
                this.$emit("on-selectRow-change",this.selTableData);
            },
        }

    }
</script>
<style scoped>
    /deep/ .el-scrollbar__wrap{
    overflow-x:hidden
}
</style>